import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { loginApi, logoutApi } from "@/api/user";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken() || "", // 从缓存获取token
  }),
  actions: {
    // 登录
    login(loginData) {
      return (async () => {
        const response = await loginApi(loginData);
        const { data } = response;
        // 存储token到内存和缓存
        this.token = data.token;
        setToken(data.token);
        return response;
      })();
    },
    // 登出
    async logout() {
      try {
        const res = await logoutApi({});
        return res;
      } catch (error) {
        console.error(" logout 接口请求失败:", error);
        throw error; // 抛出错误，让调用处的 catch 能捕获
      }
    },
    // 重置token
    resetToken() {
      return new Promise((resolve) => {
        this.token = ""; // 清除内存中的token
        removeToken(); // 清除缓存中的token
        resolve();
      });
    },
    // 其他action...
  },
});
